﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RestSharp;

namespace Openapi.Weibo.Api
{
    public abstract class ApiBase
    {
        private RestApi _restApi;

        public ApiBase(RestApi rest)
        {
            if (rest.Authenticator == null)
            {
                throw new ArgumentException("未授权的上下文请求", "RestApi.Authenticator");
            }
            _restApi = rest;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="resource"></param>
        /// <param name="httpMethod"></param>
        /// <param name="params"></param>
        /// <returns></returns>
        internal T ExecuteApi<T>(string resource, Method httpMethod=Method.POST, params Parameter[] @params) where T : new()
        {
            if (String.IsNullOrEmpty(resource))
                throw new ArgumentNullException("resource");
            RestRequest request = new RestRequest(resource,httpMethod);
            request.AddRangeParameter(@params);
            var result= _restApi.Execute<T>(request);
            if (result.ResponseStatus == ResponseStatus.None 
                || result.ResponseStatus == ResponseStatus.Completed)
            {
                return result.Data;
            }
            throw result.ErrorException;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="resource"></param>
        /// <param name="httpMethod"></param>
        /// <param name="params"></param>
        /// <returns></returns>
        internal T ExecuteApi<T>(string resource, Method httpMethod, IDictionary<String,Object> @params) where T : new()
        {
           return this.ExecuteApi<T>(resource, httpMethod, @params.ToParameterArry());
        }
    }
}
